
package com.bear.cmcc.NetTestHTTP.ui.activity;

import java.util.ArrayList;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;
import android.widget.TextView;

import com.bear.cmcc.NetTestHTTP.R;
import com.bear.cmcc.NetTestHTTP.component.NetTestCellInfoBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestRoundInfoBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestTimesInfoBean;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.constant.NetTestDBConstant;
import com.bear.cmcc.NetTestHTTP.constant.NetTestDBConstant.TestTimesFiledName;
import com.bear.cmcc.NetTestHTTP.ui.adapter.DetailAdapter;
import com.bear.cmcc.NetTestHTTP.ui.view.PullToRefreshView;
import com.bear.cmcc.NetTestHTTP.ui.view.PullToRefreshView.OnFooterRefreshListener;
import com.bear.cmcc.NetTestHTTP.ui.view.PullToRefreshView.OnHeaderRefreshListener;
import com.bear.cmcc.NetTestHTTP.util.MyCommonUtil;
import com.bear.cmcc.NetTestHTTP.util.NetTestUtil;

public class NetTestDetailActivity extends AbstractActivity implements OnHeaderRefreshListener,
OnFooterRefreshListener {
	PullToRefreshView mPullToRefreshView;

	private TextView netType = null;

	/**
	 * 测试开始时间
	 */
	private TextView time = null;

	/**
	 * 测试结束时间
	 */
	private TextView time_end = null;

	private TextView max_speed = null;

	private TextView min_speed = null;

	private TextView average_speed = null;

	/**
	 * 抖动强度
	 */
	private TextView shake = null;

	/**
	 * 服务器名称
	 */
	private TextView service_name = null;

	private ListView listViewDetail;

	private DetailAdapter listViewDetailAdapter;

	private String[] showCellName = null;

	// private TextView cell_comple = null;// 接通率
	//
	// /**
	// * 掉线率
	// */
	// private TextView drop_rate = null;

	/**
	 * 经历小区数量
	 */
	private TextView cell_number = null;

	private MyHander myHander = new MyHander();

	private int pid = 0;

	private int number = 1;

	private int bottomIdx = 0;

	private String forward = null;

	private String gap = " : ";

	private ArrayList<NetTestTimesInfoBean> listTimes;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		loadBottomBar();
		addGoBackButton();
		setTitle(R.string.title_detail);
		setContentView(R.layout.activity_detail);

		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);

		initializeView();
		if (getIntent() != null) {
			pid = getIntent().getIntExtra(NetTestDBConstant.TestRoundFiledName.pid, 0);
			number = getIntent().getIntExtra(TestTimesFiledName.number, 1);
			bottomIdx = getIntent().getIntExtra(MyCommonConstant.BottomIdxCode.bottom_dis, 0);
			forward = getIntent().getStringExtra("forward");
		}

		if (forward != null && forward.equals("up")) {
			listTimes=NetTestUtil.getNetTestTimesUpInfoByRound(this,pid);
		} else {
			listTimes=NetTestUtil.getNetTestTimesInfoByRound(this,pid);
		}

		choseBottomItemIndex(bottomIdx);
		// 加载数据。
		myHander.sendEmptyMessage(refresh_data);

	}

	@Override
	protected void onStart()
	{
		choseBottomItemIndex(bottomIdx);
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		if (myHander != null) {
			myHander.removeMessages(refresh_data);
			myHander = null;
		}
		super.onDestroy();
	}

	/**
	 * 初始化显示控件。
	 */
	 private void initializeView() {
		 // 这个顺序在refreshData有用到
		 showCellName = new String[] {
				 getString(R.string.cellName), getString(R.string.detail_cell_lac),
				 getString(R.string.detail_cell_ci), getString(R.string.detail_cell_ave),
				 getString(R.string.detail_cell_min), getString(R.string.detail_cell_max),
				 getString(R.string.city_top_slide_drop_rate),
				 getString(R.string.city_top_slide_call_complete)

		 };

		 netType = (TextView) findViewById(R.id.tv_detail_netType_value);
		 /**
		  * 测试开始时间
		  */
		 time = (TextView) findViewById(R.id.tv_detail_time_value);

		 time_end = (TextView) findViewById(R.id.tv_detail_time_value_end);

		 max_speed = (TextView) findViewById(R.id.tv_detail_collect_max_value);

		 min_speed = (TextView) findViewById(R.id.tv_detail_collect_min_value);

		 average_speed = (TextView) findViewById(R.id.tv_detail_collect_ave_value);
		 /**
		  * 抖动强度
		  */
		 shake = (TextView) findViewById(R.id.tv_detail_collect_wav_value);
		 /**
		  * 服务器名称
		  */
		 service_name = (TextView) findViewById(R.id.tv_detail_collect_server_value);

		 listViewDetail = (ListView) findViewById(R.id.listViewCellDetail);
		 listViewDetailAdapter = new DetailAdapter(this, new ArrayList<String[]>());
		 listViewDetail.setAdapter(listViewDetailAdapter);

		 // cell_comple = (TextView)
		 // findViewById(R.id.tv_detail_collect_complete_value);
		 //
		 // drop_rate = (TextView)
		 // findViewById(R.id.tv_detail_collect_drop_value);

		 cell_number = (TextView) findViewById(R.id.tv_detail_collect_cell_number_value);

	 }

	 @Override
	 public void onFooterRefresh(PullToRefreshView view) {
		 mPullToRefreshView.postDelayed(new Runnable() {

			 @Override
			 public void run() {
				 myHander.sendEmptyMessage(refresh_data_dowm);
				 mPullToRefreshView.onFooterRefreshComplete();
			 }
		 }, 1000);
	 }

	 @Override
	 public void onHeaderRefresh(PullToRefreshView view) {
		 mPullToRefreshView.postDelayed(new Runnable() {

			 @Override
			 public void run() {
				 myHander.sendEmptyMessage(refresh_data_up);
				 mPullToRefreshView.onHeaderRefreshComplete();

			 }
		 }, 1000);

	 }

	 /**
	  * 刷新数据。
	  */
	  private void refreshData(int number) {
		  try {
			  NetTestTimesInfoBean netTimes;
			  if (number > 0) {
				  if (forward != null && forward.equals("up")) {
					  netTimes=listTimes.get(number-2);
				  }  else {
					  netTimes=listTimes.get(number-1);
				  }
				  if (netTimes != null) {

					  netType.setText(gap + netTimes.getNetType());
					  /**
					   * 测试开始时间
					   */
					  time.setText(gap + ""+number);
					  time_end.setText(gap + ""+listTimes.size());

					  max_speed.setText(gap + MyCommonUtil.getFormatString(netTimes.getMaxSpeed()));

					  min_speed.setText(gap + MyCommonUtil.getFormatString(netTimes.getMinSpeed()));

					  average_speed.append(((gap
							  + MyCommonUtil.getFormatString(netTimes.getAverageSpeed()))));
					  /**
					   * 抖动强度
					   */
					  // shake.setText(gap
					  // + NetTestUtil.getWaveShakeStrong(roundInfo.getMaxSpeed(),
					  // roundInfo.getMinSpeed()));

					  //                    shake.setText(gap
					  //                            + NetTestUtil.getWaveShakeStrong(NetTestDetailActivity.this,
					  //                            		netTimes.getPID()));
					  shake.setText(gap
							  + netTimes.getWaveShakeStrong());
					  /**
					   * 服务器名称
					   */
					  service_name.setText(gap + netTimes.getDownServer());

					  // cell_comple.setText(gap);
					  //
					  // drop_rate.setText(gap );

					  cell_number.setText(gap + 0);

					  if (listViewDetailAdapter != null) {
						  ArrayList<String[]> values = new ArrayList<String[]>();
						  ArrayList<NetTestCellInfoBean> cells = NetTestUtil
								  .getNetTestCellInfosByTimes(this, netTimes.getPID());
						  if (cells != null) {
							  cell_number.setText(gap + cells.size());
							  for (NetTestCellInfoBean cell : cells) {
								  values.add(new String[] {
										  showCellName[0], gap + cell.getCellName()
								  });
								  values.add(new String[] {
										  showCellName[1], gap + cell.getLac()
								  });
								  values.add(new String[] {
										  showCellName[2], gap + cell.getCi()
								  });
								  values.add(new String[] {
										  showCellName[5], gap + MyCommonUtil.getFormatString(cell.getMaxSpeed())
								  });

								  values.add(new String[] {
										  showCellName[4], gap + MyCommonUtil.getFormatString(cell.getMinSpeed())
								  });
								  values.add(new String[] {
										  showCellName[3], gap + MyCommonUtil.getFormatString(cell.getAverageSpeed())
								  });

								  values.add(new String[] {
										  showCellName[6],
										  gap
										  + NetTestUtil.getCellDropPercent(this,
												  cell.getLac(), cell.getCi())
								  });

								  values.add(new String[] {
										  showCellName[7],
										  gap
										  + NetTestUtil.getCellConnectPercent(this,
												  cell.getLac(), cell.getCi())
								  });
								  break;// 只是显示一个数据
							  }
						  }
						  listViewDetailAdapter.clearData();
						  listViewDetailAdapter.addData(values);
					  }
				  }

			  }
		  } catch (Exception e) {
			  e.printStackTrace();
		  }
	  }

	  /**
	   * 获取前一轮数据(比较老的数据)。
	   */
	  private void getBeforeData() {
		  try {
			  //            ArrayList<NetTestRoundInfoBean> beans = NetTestUtil.getNetTestRoundsInfos(this, false);
			  //            if (beans == null || beans.size() == 1) {
			  //                MyCommonUtil.showMessage(this, R.string.not_up_round_data);
			  //                return;
			  //            }
			  //            // 获取最接近pid的值，并且是小于pid
			  //            int minPid = 0;
			  //            for (NetTestRoundInfoBean element : beans) {
			  //                if (element.getPID() < pid) {
			  //                    if (element.getPID() > minPid) {
			  //                        minPid = element.getPID();
			  //                    }
			  //                }
			  //            }
			  //
			  //            if (minPid == pid || pid == 0 || minPid == 0) {
			  //                MyCommonUtil.showMessage(this, R.string.not_up_round_data);
			  //                return;
			  //            }
			  //
			  //            pid = minPid;

			  number++;
			  if(number<=listTimes.size()){
				  myHander.sendEmptyMessage(refresh_data);
			  }else{
				  number=listTimes.size();
				  MyCommonUtil.showMessage(this, R.string.not_down_round_data);
			  }
		  } catch (Exception e) {
			  e.printStackTrace();
		  }

	  }

	  /**
	   * 获取下一轮数据。
	   */
	  private void getNextData() {
		  try {
			  //            ArrayList<NetTestRoundInfoBean> beans = NetTestUtil.getNetTestRoundsInfos(this, false);
			  //            if (beans == null || beans.size() == 1) {
			  //                MyCommonUtil.showMessage(this, R.string.not_down_round_data);
			  //                return;
			  //            }
			  //            // 获取最接近pid的值，并且是大于pid
			  //            int minPid = 0;
			  //            for (NetTestRoundInfoBean element : beans) {
			  //                if (element.getPID() > pid) {
			  //                    if (minPid == 0) {
			  //                        minPid = element.getPID();
			  //                    }
			  //
			  //                    if (element.getPID() < minPid) {
			  //                        minPid = element.getPID();
			  //                    }
			  //                }
			  //            }
			  //
			  //            if (minPid == pid || (pid == 0) || minPid == 0) {
			  //                MyCommonUtil.showMessage(this, R.string.not_down_round_data);
			  //                return;
			  //            }
			  //
			  //            pid = minPid;
			  number--;
			  if(number>0){
				  myHander.sendEmptyMessage(refresh_data);
			  }else{
				  number=1;
				  MyCommonUtil.showMessage(this, R.string.not_up_round_data);
			  }
		  } catch (Exception e) {
			  e.printStackTrace();
		  }
	  }

	  /**
	   * 获取次中的网络类型（去掉重复的）。
	   * 
	   * @param roundInfo
	   * @return
	   */
	  private String getAllNetType(NetTestRoundInfoBean roundInfo) {
		  String allNetType = "";
		  try {
			  ArrayList<NetTestTimesInfoBean> times = NetTestUtil.getNetTestTimesInfoByRound(this,
					  roundInfo.getPID());
			  if (times != null && times.size() > 0) {
				  // 先读取一天数据。
				  allNetType = times.remove(0).getNetType();
				  for (NetTestTimesInfoBean element : times) {
					  if (!allNetType.contains(element.getNetType())) {
						  if (element.getNetType() != null) {
							  allNetType = allNetType + ";" + element.getNetType();
						  }
					  }

				  }
			  }
		  } catch (Exception e) {
			  e.printStackTrace();
		  }
		  return allNetType;
	  }

	  private int refresh_data_dowm = 3;

	  private int refresh_data = 2;

	  private int refresh_data_up = 1;

	  class MyHander extends Handler {
		  @Override
		  public void handleMessage(Message msg) {
			  if (msg == null) {
				  return;
			  }
			  if (refresh_data == msg.what) {
				  refreshData(number);
				  return;
			  }

			  if (refresh_data_dowm == msg.what) {
				  getBeforeData();
				  return;
			  }

			  if (refresh_data_up == msg.what) {
				  getNextData();
				  return;
			  }

		  }
	  }
}
